﻿using System;

namespace MathService.DSP.Signals
{
    public partial class DigitalSignal
    {
        /* - Статические методы ----------------------------------------------------------------------- */

        public static DigitalSignal CreateDataReferenced(double dx, double[] Samples)
        {
            return CreateDataReferenced(dx, 0, Samples);
        }

        public static DigitalSignal CreateDataReferenced(double dx, double x0, double[] Samples)
        {
            var lv_Signal = new DigitalSignal(dx)
                    {
                        f_x0 = x0,
                        f_Interval = new Interval(x0, Samples.Length*dx),
                        f_Samples = Samples
                    };

        	return lv_Signal;
        }

        public static DigitalSignal CreateDataReferenced(DigitalSignal s)
        {
            return (DigitalSignal)s.MemberwiseClone();
        }

        public static DigitalSignal CreateDelayed(DigitalSignal s, double Delay)
        {
            var lv_Result = CreateDataReferenced(s);
            lv_Result.x0 += Delay;
            return lv_Result;
        }

        #region Груповые операции

        public static void AlignSignals(DigitalSignal[] Signals)
        {
             
            var lv_SignalCount = Signals.Length;
            var x0 = double.NegativeInfinity;
            var x1 = double.PositiveInfinity;
            for(var i = 0; i < lv_SignalCount; i++)
            {
                var lv_SignalX0 = Signals[i].x0;
                var lv_SignalX1 = Signals[i].x1;

                if(lv_SignalX0 > x0) x0 = lv_SignalX0;
                if(lv_SignalX1 < x1) x1 = lv_SignalX1;
            }

            var lv_Length = x1 - x0;
            for(var i = 0; i < lv_SignalCount; i++)
                if(Signals[i].x0 != x0 || Signals[i].Length != lv_Length)
                {
                    var lv_OldSignal = Signals[i];
                    var lv_SignalSamples = lv_OldSignal.Samples.GetSubArray(lv_OldSignal.SamplePos(x0),
                        (int)(lv_Length / lv_OldSignal.dx));
                    Signals[i] = new DigitalSignal(lv_OldSignal.dx, x0, lv_SignalSamples) {Name = lv_OldSignal.Name};
                }


        }

        public static void Set_dx(double dx, params DigitalSignal[] Signals)
        {
        	var i_Length = Signals.Length;
        	for(var i = 0; i < i_Length; i++)
                Signals[i].dx = dx;
        }

    	public static void Set_x0(double x0, params DigitalSignal[] Signals)
    	{
    		var i_Length = Signals.Length;
    		for(var i = 0; i < i_Length; i++)
                Signals[i].x0 = x0;
    	}

    	public static void Resample(double dx, params DigitalSignal[] Signals)
    	{
    		var i_Length = Signals.Length;
    		for(var i = 0; i < i_Length; i++)
                Signals[i] = Signals[i].Rediscret(dx);
    	}

    	#endregion
    }
}

